package com.learn.im.servcie.impl;

import ch.qos.logback.core.util.FileUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.learn.im.domain.Chat;
import com.learn.im.domain.ChatAttach;
import com.learn.im.domain.FileMessage;
import com.learn.im.servcie.ChatAttachService;
import com.learn.im.servcie.ChatService;
import com.learn.im.servcie.MessageHandler;
import com.learn.im.websocket.IMServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.websocket.Session;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @author Emp
 * @version :    1.0
 */
@Service(value = "FILE")
@Slf4j
public class FileMessageHandler implements MessageHandler {

    @Value("${im.storage.path}")
    private String FILE_PATH;

    @Resource
    private ChatService chatService;
    @Resource
    private ChatAttachService chatAttachService;

    @Override
    public void handle(Chat chat, IMServer client) {
        JSONObject obj = JSON.parseObject(chat.getContent());
        Integer index = obj.getInteger("index");
        try {
            if (index == 0) {
                // 获取文件详细数据
                FileMessage fileMessage = FileMessage.parse(chat);
                // 获取新文件名
                String realName = UUID.randomUUID() + "-" + fileMessage.getOriginName();
                // 存储路径
                String filePath = createFilePath() + realName;
                File file = new File(FILE_PATH + filePath);
                fileMessage.setFile(file);
                fileMessage.setFilePath(filePath);
                fileMessage.setRealName(realName);
                client.setFileInstance(fileMessage);
                client.command("next");
            } else if (index == -1) {
                // 文件传输结束
                log.info("文件传输结束,待检查");
                final FileMessage finalFile = client.getFileInstance();
                // 判断文件大小是否正确,不正确返回文件传输异常并删除文件
                if (!(finalFile.getFile().length() == finalFile.getSize())) {
                    log.error("文件不完整!");
                    client.command("file_check_error");
                    // 删除文件
                    boolean delete = finalFile.getFile().delete();
                } else {
                    // 所有分片上传完毕
                    log.info("文件上传成功");
                    // 发送文件二进制给接收方/发送文件下载路径给接收方
                    boolean flag = this.doSend(client);
                    // 上传成功,保存数据库
                    finalFile.getChat().setStatus(flag);
                    chatService.save(finalFile.getChat());
                    ChatAttach attach = finalFile.convert();
                    chatAttachService.save(attach);
                    // 上传成功返回success
                    client.command("file_upload_success");
                }
            }else {
                log.info("传输文件第{}部分",index);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public String createFilePath() {
        SimpleDateFormat format = new SimpleDateFormat("yyyy" + File.separator + "MM");
        return format.format(new Date()) + File.separator;
    }

    public boolean doSend(IMServer client){
        return client.sendFile();
    }
}
